package cn.percent.mvcframework.servlet;

import cn.percent.mvcframework.annotations.*;
import cn.percent.mvcframework.pojo.Handler;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames =  new ArrayList<>();

    private HashMap<String,Object> ioc = new HashMap<String,Object>();

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 加载配置文件 springnvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");

        doLoadConfig(contextConfigLocation);

        // 扫描包，生成所有class列表
        doScan(properties.getProperty("scanPackage"));

        // 初始化bean对象（实现IoC容器）
        doInstance();

        // 依赖注入
        doAutoWired();

        // 构造一个handlerMapping处理器映射器，将配置好的url和method建立映射关系
        initHandlerMapping();
    }

    private void initHandlerMapping() {
        if(ioc.isEmpty()) return;
        //System.out.println(ioc);
        for(Map.Entry<String,Object> entry : ioc.entrySet()){
            Class<?> aClass = entry.getValue().getClass();
            if(!aClass.isAnnotationPresent(percentController.class)) continue;

            String baseUrl = "";
            if(aClass.isAnnotationPresent(percentRequestMapping.class)){
                percentRequestMapping annotation = aClass.getAnnotation(percentRequestMapping.class);
                baseUrl = annotation.value();

            }
            // 获取方法
            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                // 方法没有标识percentRequestMapping不处理
                if(!method.isAnnotationPresent(percentRequestMapping.class)) continue;
                // 如果标识了percentRequestMapping则处理
                percentRequestMapping annotation = method.getAnnotation(percentRequestMapping.class);
                String methodUrl = annotation.value();
                String url = baseUrl + methodUrl;




                // 把method所有信息及url封装为一个handler
                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));

                // 计算方法的参数位置信息
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        // 如果是request和response对象，那么参数名称写成HttpServletRequest和HttpServletRespose
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j);
                    } else {
                        handler.getParamIndexMapping().put(parameter.getName(),j);
                    }
                }

                // 获取权限
                if (method.isAnnotationPresent(percentSecurity.class)) {
                    percentSecurity security = method.getAnnotation(percentSecurity.class);
                    String[] securityValue = security.value();
                    //System.out.println(securityValue);
                    handler.setAuthority(new HashSet(Arrays.asList(securityValue)));
                }



                handlerMapping.add(handler);
            }
        }


    }

    private void doAutoWired() {
        if (ioc.isEmpty()) return;

        for (Map.Entry<String,Object> entry : ioc.entrySet()) {
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                Field declaredField = declaredFields[i];
                if(!declaredField.isAnnotationPresent(percentAutowired.class)) continue;

                percentAutowired annotation = declaredField.getAnnotation(percentAutowired.class);
                String beanName  = annotation.value();
                if("".equals(beanName.trim())) {
                    // 没有配置具体的bean id，需要根据字段类型注入
                    beanName = declaredField.getType().getName();
                }

                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(),ioc.get(beanName));
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private void doInstance() {
        if (classNames.size() == 0) return ;
        try {
            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i);
                // 反射
                Class<?> aClass = Class.forName(className);
                // 区分controller,service
                //System.out.println(aClass);
                if (aClass.isAnnotationPresent(percentController.class)) {
                    // controller的id此处不做过多处理，不取value，拿类的首字母小写作为id
                    String simpleName = aClass.getSimpleName();

                    String lowerFirstSimpleName = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName,o);

                } else if(aClass.isAnnotationPresent(percentService.class)) {
                    percentService annotation = aClass.getAnnotation(percentService.class);
                    String beanName = annotation.value();
                    // 如果指定了id，就以指定的值为准
                    if(!"".equals(beanName.trim())) {
                        ioc.put(beanName,aClass.newInstance());
                    } else {
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName,aClass.newInstance());
                    }
                    // 将aClass实现的接口作为beanName存入ioc
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        ioc.put(anInterface.getName(),aClass.newInstance());
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 扫描包
    private void doScan(String scanPackage) {
        //System.out.println(scanPackage);
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.","/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                doScan(scanPackage + "." +file.getName());
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class","");
                //System.out.println(className);
                classNames.add(className);
            }
        }
    }

    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if ('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return  String.valueOf(chars);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //uper.doPost(req, resp);
        // 根据url处理请求，找到对应的method方法，进行调用
        String requestURI = req.getRequestURI();
        //System.out.println(requestURI);
        // 根据uri获取到能够处理请求的handler
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }

        // 参数绑定
        // 获取所有类型数组，这个数组长度就是我们最后要传入的args数据的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        // 根据上述数组长度创建一个新的数据（参数数组，是要传入反射调用的）
        Object[] paraValues = new Object[parameterTypes.length];

        // 以下就是为了向参数数组中塞值，而且还得保证参数的顺序和方法中的形参顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap();


        if(!parameterMap.keySet().contains("username")){
            resp.getWriter().write("403 Forbidden! please login");
            return;
        } else if (parameterMap.get("username").length == 0) {
            resp.getWriter().write("403 Forbidden! no username");
            return;
        }else {
            String[] usernames = parameterMap.get("username");
            if(!handler.getAuthority().contains(usernames[0])){
                resp.getWriter().write("403 Forbidden! Permission denied");
                return;
            }
        }
        // 遍历request中的所有参数（填充除request和response以外的参数）
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {

            // name=1&name=2 name [1,2]
            String value = StringUtils.join(param.getValue(), ",");

            // 如果参数和方法中的参数匹配上了，填充数据
            // System.out.println(handler.getParamIndexMapping());
            if(!handler.getParamIndexMapping().containsKey(param.getKey())) continue;

            // 方法形参确实有该参数，找到它的索引位置，把对应的参数值放入paraValue
            Integer index = handler.getParamIndexMapping().get(param.getKey()); // name 在第几个位置
            paraValues[index] = value;  // 把前台传递过来的参数值填充到对应的位置去
        }
        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex] = req;

        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[responseIndex] = resp;
        // 最终调用handler的method方法
        try{
            Object invokeResult = handler.getMethod().invoke(handler.getController(), paraValues);
            resp.getWriter().write((String) invokeResult);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) return null;
        String url = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) continue;
            return handler;
        }
        return null;

    }



}
